// 颜色配置（低饱和度配色方案）
const colorPalette = [
    '#6C8EBF', // 灰蓝色
    '#82B366', // 墨绿色
    '#D6B656', // 暗金色
    '#B85450', // 砖红色
    '#7C51A1'  // 灰紫色
];

// 初始化图表
let chart1 = initLineChart();
let chart2 = initBarChart();
let chart3 = initPieChart();
let chart4 = initPanelChart(); // 初始化仪表盘
let chart5 = initAnomalyChart(); // 初始化异常流量
let chart6 = initTenMinutes(); // 初始化十分钟流量监测

// 初始化折线图（保持原有功能不变）
function initLineChart() {
    const chart = echarts.init(document.getElementById('chart1'));
    const option = {
        color: colorPalette,
        title: { text: '实时流量监测', left: 'center' },
        tooltip: { trigger: 'axis' },
        xAxis: {
            type: 'time',
            splitLine: { show: false },
            axisLabel: { color: '#999' }
        },
        yAxis: {
            type: 'value',
            splitLine: { lineStyle: { color: '#444' } },
            axisLabel: { color: '#999' }
        },
        series: [{
            name: '流量',
            type: 'line',
            smooth: true,
            symbol: 'none',
            areaStyle: { opacity: 0.2 },
            data: generateTimeSeriesData()
        }]
    };
    chart.setOption(option);
    
    // 模拟实时数据更新
    setInterval(() => {
        const data = chart.getOption().series[0].data;
        const newData = [
            ...data.slice(1),
            {
                name: new Date(),
                value: [
                    new Date(),
                    Math.floor(Math.random() * 1000) + 500
                ]
            }
        ];
        chart.setOption({ series: [{ data: newData }] });
    }, 5000);
    
    return chart;
}

// 初始化柱状图（保持原有功能不变）
function initBarChart() {
    const chart = echarts.init(document.getElementById('chart2'));
    const ports = ['80', '443', '22', '53', '3389'];
    const option = {
        color: colorPalette,
        title: { text: '端口流量分布', left: 'center' },
        tooltip: { trigger: 'axis' },
        xAxis: {
            type: 'category',
            data: ports,
            axisLabel: { color: '#999' }
        },
        yAxis: {
            type: 'value',
            splitLine: { lineStyle: { color: '#444' } },
            axisLabel: { color: '#999' }
        },
        series: [{
            type: 'bar',
            data: ports.map(() => Math.floor(Math.random() * 1000) + 200),
            barWidth: '60%',
            itemStyle: { borderRadius: [4, 4, 0, 0] }
        }]
    };
    chart.setOption(option);
    return chart;
}

// 初始化饼图（保持原有功能不变）
function initPieChart() {
    const chart = echarts.init(document.getElementById('chart3'));
    const protocols = ['TCP', 'UDP', 'ICMP', 'HTTP', 'HTTPS'];
    const option = {
        color: colorPalette,
        title: { text: '协议分布', left: 'center' },
        tooltip: { trigger: 'item' },
        series: [{
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            label: {
                show: true,
                formatter: '{b}: {d}%',
                color: 'black'
            },
            data: protocols.map(name => ({
                name,
                value: Math.floor(Math.random() * 500) + 100
            }))
        }]
    };
    chart.setOption(option);
    return chart;
}

// 生成时间序列数据（最近10分钟）
function generateTimeSeriesData() {
    const data = [];
    const now = Date.now();
    for (let i = 9; i >= 0; i--) {
        data.push({
            name: new Date(now - i * 60000),
            value: [
                new Date(now - i * 60000),
                Math.floor(Math.random() * 1000) + 500
            ]
        });
    }
    return data;
}

// 初始化仪表盘（关键修改部分）
function initPanelChart() {
    // 仪表盘数据配置
    const gauges = [
        { label: '负载状态', value: '100%', subInfo: null },
        { label: 'CPU使用率', value: '100%', subInfo: null },
        { label: '内存使用率', value: '100%', subInfo: null },
        { label: '运行阻塞', value: '100%', subInfo: '2核心' }
    ];

    // 获取仪表盘容器（确保HTML中存在id="chart4"的容器）
    const container = document.getElementById('chart4');
    
    // 创建外层仪表盘容器
    const dashboard = document.createElement('div');
    dashboard.className = 'dashboard'; // 应用CSS样式

    // 动态生成每个仪表盘
    gauges.forEach(gauge => {
        // 创建单个仪表盘容器
        const gaugeDiv = document.createElement('div');
        gaugeDiv.className = 'gauge';

        // 创建环形进度条
        const ring = document.createElement('div');
        ring.className = 'ring';
        
        // 创建中心遮罩层
        const mask = document.createElement('div');
        mask.className = 'mask';

        // 数值显示
        const value = document.createElement('div');
        value.className = 'value';
        value.textContent = gauge.value;

        // 标签文字
        const label = document.createElement('div');
        label.className = 'label';
        label.textContent = gauge.label;

        // 附加信息（如果有）
        if (gauge.subInfo) {
            const subInfo = document.createElement('div');
            subInfo.className = 'sub-info';
            subInfo.textContent = gauge.subInfo;
            mask.appendChild(subInfo);
        }

        // 组装元素
        mask.appendChild(value);
        mask.appendChild(label);
        gaugeDiv.appendChild(ring);
        gaugeDiv.appendChild(mask);
        dashboard.appendChild(gaugeDiv);
    });

    // 将仪表盘添加到容器
    container.appendChild(dashboard);

    // 返回空对象保持接口一致性（因非ECharts图表）
    return { resize: () => {} };
}

// 初始化异常流量图表（保持原有功能不变）
function initAnomalyChart() {
    const chart = echarts.init(document.getElementById('chart5'));
    const option = {
        color: ['#B85450'],
        title: { text: '异常流量趋势分析', left: 'center' },
        tooltip: { trigger: 'axis' },
        xAxis: {
            type: 'category',
            data: Array.from({ length: 200 }, (_, i) => i),
            axisLabel: { color: '#999' },
            splitLine: { show: false }
        },
        yAxis: {
            type: 'value',
            min: 0,
            max: 2200,
            axisLabel: { color: '#999' },
            splitLine: { lineStyle: { color: '#444' } }
        },
        series: [{
            name: '流量',
            type: 'line',
            smooth: true,
            symbol: 'none',
            lineStyle: {
                width: 2,
                shadowColor: 'rgba(184,84,80,0.3)',
                shadowBlur: 10,
                shadowOffsetY: 8
            },
            areaStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                    offset: 0,
                    color: 'rgba(184,84,80,0.6)'
                }, {
                    offset: 1,
                    color: 'rgba(184,84,80,0.1)'
                }])
            },
            data: generateWaveData()
        }]
    };

    chart.setOption(option);
    return chart;
}

// 初始化十分钟流量监测（保持原有功能不变）
function initTenMinutes() {
    const chart = echarts.init(document.getElementById('chart6'));
    const option = {
        color: ['#9961b9'],
        title: { text: '近十分钟流量监测', left: 'center' },
        tooltip: { trigger: 'axis' },
        xAxis: {
            type: 'time',
            splitLine: { show: false },
            axisLabel: { color: '#999' }
        },
        yAxis: {
            type: 'value',
            splitLine: { lineStyle: { color: '#444' } },
            axisLabel: { color: '#999' }
        },
        series: [{
            name: '流量',
            type: 'line',
            smooth: true,
            symbol: 'none',
            areaStyle: { opacity: 0.2 },
            data: generateTimeSeriesData()
        }]
    };

    chart.setOption(option);
    return chart;
}

// 生成波形数据（先升后降）
function generateWaveData() {
    const data = [];
    const peak = 2000;
    const duration = 200;
    for (let i = 0; i < duration; i++) {
        let value;
        if (i < duration / 2) {
            value = (peak * 2 * i) / duration;
        } else {
            value = (peak * 2 * (duration - i)) / duration;
        }
        data.push(value + Math.random() * 50);
    }
    return data;
}

// 窗口resize统一处理
window.addEventListener('resize', () => {
    // 传统图表需要resize
    [chart1, chart2, chart3, chart5, chart6].forEach(chart => chart.resize());
});
// 获取所有仪表盘的环形进度条
const rings = document.querySelectorAll('.ring');

// 更新仪表盘的进度
function updateGaugeProgress(ringElement, percent) {
    const degrees = (percent / 100) * 360;
    ringElement.style.background = `conic-gradient(
        #55a1e9 0deg,
        #55a1e9 ${degrees}deg,
        transparent ${degrees}deg,
        transparent 360deg
    )`;
}

// 更新仪表盘的数值
function updateGaugeValue(valueElement, newValue) {
    valueElement.textContent = `${newValue}%`;
}

// 模拟动态更新
function simulateDynamicUpdates() {
    const valueElements = document.querySelectorAll('.value');

    setInterval(() => {
        // 随机生成新的数值（0% - 100%）
        const newValues = [
            Math.floor(Math.random() * 100),
            Math.floor(Math.random() * 100),
            Math.floor(Math.random() * 100),
            Math.floor(Math.random() * 100)
        ];

        // 更新每个仪表盘的进度和数值
        rings.forEach((ring, index) => {
            updateGaugeProgress(ring, newValues[index]);
            updateGaugeValue(valueElements[index], newValues[index]);
        });
    }, 2000); // 每2秒更新一次
}

// 初始化动态效果
simulateDynamicUpdates();

function getRingColor(percent) {
    if (percent < 30) return '#82B366'; // 绿色
    if (percent < 70) return '#D6B656'; // 黄色
    return '#B85450'; // 红色
}

function updateGaugeProgress(ringElement, percent) {
    const degrees = (percent / 100) * 360;
    const color = getRingColor(percent);
    ringElement.style.background = `conic-gradient(
        ${color} 0deg,
        ${color} ${degrees}deg,
        transparent ${degrees}deg,
        transparent 360deg
    )`;
}

async function fetchDataAndUpdate() {
    const response = await fetch('/api/status');
    const data = await response.json();
    rings.forEach((ring, index) => {
        updateGaugeProgress(ring, data.values[index]);
        updateGaugeValue(valueElements[index], data.values[index]);
    });
}

// setInterval(fetchDataAndUpdate, 5000); // 每5秒更新一次